package com.koron.standard.deviceBrand.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.koron.standard.deviceBrand.bean.po.BrandStock;
import com.koron.standard.deviceBrand.service.BrandStockService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Set;

/**
 * @author jzp
 * @since 2022/5/26
 */
@Slf4j
public class BrandStockListener extends AnalysisEventListener<BrandStock> {
    private static final int BATCH_COUNT = 100;

    private List<BrandStock> brandStockList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private final BrandStockService brandStockService;
    private final Set<String> nameSet;

    public BrandStockListener(BrandStockService brandStockService) {
        this.brandStockService = brandStockService;
        nameSet = brandStockService.listAllName();
    }

    @Override
    public void invoke(BrandStock data, AnalysisContext context) {
        // 重复品牌简称忽略
        if (nameSet.contains(data.getName())) {
            return;
        }
        data.setNum(0);
        brandStockList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (brandStockList.size() >= BATCH_COUNT) {
            saveBrandStock();
            // 存储完成清理 list
            brandStockList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveBrandStock();
    }

    private void saveBrandStock() {
        if (brandStockList.size() == 0) {
            return;
        }
        // 1.1 获取当天最大编码
        log.info("{}条数据，开始存储数据库！", brandStockList.size());
        brandStockService.saveBatch(brandStockList);
        log.info("存储数据库成功！");
    }

}
